﻿using STT.Admin;
using STT.Business;
using STT.Entities;
using STT.Layer.Connection;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace STT.Profile.UserControlsGV
{
    public partial class UcDanhSachHocVien : System.Web.UI.UserControl
    {
        ToolBox tb = new ToolBox();
        string last;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                LoadDDLKhoahoc();

        }
        private void LoadDDLKhoahoc()
        {
            Methods.KhoaHoc2(ref ddlkhoahoc, Session["Magv"].ToString());
        }
        void ThongBao(string Loi)
        {
            ScriptManager.RegisterClientScriptBlock(this, GetType(), "Thông báo!","<script>alert('" + Loi + "')</script>", false);
        }
        protected void ddlkhoahoc_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ddlkhoahoc.SelectedItem.ToString() == "---------Chọn---------")
                {
                    ThongBao("Bạn hãy chọn khóa học để xem..!");
                }
                else
                {
                    Methods.LopHocByKhoaHocID(ref ddllophoc, ddlkhoahoc.SelectedValue.ToString(), Session["Magv"].ToString());
                }
            }
            catch (Exception ex)
            {
                Response.Write("");
            }
        }

        protected void ddllophoc_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {

                if (ddllophoc.SelectedItem.ToString() == "---------Chọn---------")
                {
                    ThongBao("Bạn hãy chọn lớp học để xem..!");

                }
                else
                {
                    LoadByLopHoc();
                }
            }
            catch (Exception ex)
            {
                Response.Write("");
            }
        }
        private void LoadByLopHoc()
        {
            
            ETbHocVien hv = new ETbHocVien();
            hv.MaLop = int.Parse(ddllophoc.SelectedValue.ToString());
            DataTable dt = BTbHocVien.SelectByLop(hv);
            if (dt.Rows.Count > 0)
            {
                gvDiemHV.DataSource = dt;
                gvDiemHV.DataBind(); 
                pnbangdiem.Visible = true;
            }
            else pnbangdiem.Visible = false;
        }
        protected void gvDiemHV_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            if (ddllophoc.SelectedItem.ToString() != "---------Chọn---------")
            {
                gvDiemHV.PageIndex = e.NewPageIndex;
                LoadByLopHoc();
            }
        }
        protected void ddlchucvutronglop_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //ImageButton img = sender as ImageButton;
                DropDownList ddl = sender as DropDownList;
                foreach (GridViewRow row in gvDiemHV.Rows)
                {
                    ImageButton imgaccept = row.FindControl("imgaccept") as ImageButton;
                    Control ctrl = row.FindControl("ddlchucvutronglop") as DropDownList;
                    DropDownList ddlchucvu = ((DropDownList)row.FindControl("ddlchucvutronglop"));
                    if (ctrl != null)
                    {
                        DropDownList ddl1 = (DropDownList)ctrl;
                        if (ddl.ClientID == ddl1.ClientID)
                        {
                            if (ddlchucvu.SelectedValue.ToString() == "0")
                                imgaccept.Visible = false;
                            else
                            {
                                imgaccept.Visible = true;
                            }
                        }
                    }
                }
            }
            catch { }
        }
        protected void gvDiemHV_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    DropDownList ddlchucvu = (DropDownList)e.Row.FindControl("ddlchucvutronglop");
                    ImageButton imgdelete = (ImageButton)e.Row.FindControl("imgdelete");
                    LoadChucVuHVTrongLop(ddlchucvu);
                    if ((e.Row.FindControl("lblchucvutronglop") as Label).Text != "Không")
                    { 
                        ddlchucvu.Items.FindByText((e.Row.FindControl("lblchucvutronglop") as Label).Text).Selected = true;
                        ddlchucvu.Enabled = false;
                        imgdelete.Visible = true;
                    }
                    DataTable dt = tb.GetDataTableById2("TbHocVien_GetChucVuTrongLopByMaLop", ddllophoc.SelectedValue.ToString());
                    if (ddlchucvu.Enabled == true)
                    {
                        LoadChucVuHVTrongLop(ddlchucvu);
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (dt.Rows[i]["ChucVuTrongLop"].ToString() == "Lớp Trưởng")
                            {
                                ddlchucvu.Items.Remove(ddlchucvu.Items.FindByText("Lớp Trưởng"));
                            }
                            if (dt.Rows[i]["ChucVuTrongLop"].ToString() == "Lớp Phó")
                            {
                                ddlchucvu.Items.Remove(ddlchucvu.Items.FindByText("Lớp Phó"));
                            }
                            if (dt.Rows[i]["ChucVuTrongLop"].ToString() == "Bí Thư")
                            {
                                ddlchucvu.Items.Remove(ddlchucvu.Items.FindByText("Bí Thư"));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write("");
            }
        }
        protected void imgaccept_Click(object sender, ImageClickEventArgs e)
        {
            try
            {

                ImageButton img = sender as ImageButton;
                foreach (GridViewRow row in gvDiemHV.Rows)
                {
                    string Mahv = gvDiemHV.DataKeys[row.RowIndex].Value.ToString();
                    ImageButton imgdelete = row.FindControl("imgdelete") as ImageButton;
                    ImageButton imgaccept = row.FindControl("imgaccept") as ImageButton;
                    DropDownList ddlchucvu2 = ((DropDownList)row.FindControl("ddlchucvutronglop"));
                    Control ctrl = row.FindControl("imgaccept") as ImageButton;
                    if (ctrl != null)
                    {
                        ImageButton img1 = (ImageButton)ctrl;
                        if (img.ClientID == img1.ClientID)
                        {
                            DataTable dt = tb.GetDataTableById4("TbHocVien_GetChucVuTrongLopByMaLopCV", ddlchucvu2.SelectedItem.ToString(), ddllophoc.SelectedValue.ToString());
                            if (ddlchucvu2.SelectedValue.ToString() != "0")
                            {
                                if (dt.Rows.Count > 0)
                                {
                                    ThongBao("Chức vụ này đã được cấp..!");
                                }
                                else
                                {
                                    imgdelete.Visible = true;
                                    imgaccept.Visible = false;
                                    ddlchucvu2.Enabled = false;
                                    BTbHocVien.UpdateChucVuHVTrongLop(new ETbHocVien
                                    {
                                        ChucVuTrongLop = ddlchucvu2.SelectedItem.ToString(),
                                        MaHV = Mahv
                                    });
                                    last = ddlchucvu2.SelectedItem.ToString();
                                }
                            }
                            else
                                ThongBao("Bạn hãy chọn chức vụ học viên..!");
                        }
                    }
                    foreach (GridViewRow row2 in gvDiemHV.Rows)
                    {
                        DropDownList ddlchucvu3 = ((DropDownList)row2.FindControl("ddlchucvutronglop"));
                        if (ddlchucvu3.Enabled == true)
                        {
                            ddlchucvu3.Items.Remove(ddlchucvu3.Items.FindByText(last));
                            imgaccept.Visible = false;
                        };
                    }
                }
            }
            catch { }
        }
        private void LoadChucVuHVTrongLop(DropDownList ddlchucvu)
        {
            ddlchucvu.Items.Clear();
            List<ListItem> items = new List<ListItem>();
            items.Add(new ListItem("Chọn", "0"));
            items.Add(new ListItem("Lớp Trưởng", "1"));
            items.Add(new ListItem("Lớp Phó", "2"));
            items.Add(new ListItem("Bí Thư", "3"));
            ddlchucvu.Items.AddRange(items.ToArray());
        }
        protected void imgdelete_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                ImageButton img = sender as ImageButton;
                foreach (GridViewRow row in gvDiemHV.Rows)
                {
                    string Mahv = gvDiemHV.DataKeys[row.RowIndex].Value.ToString();
                    ImageButton imgdelete = row.FindControl("imgdelete") as ImageButton;
                    ImageButton imgaccept = row.FindControl("imgaccept") as ImageButton;
                    DropDownList ddlchucvu = (DropDownList)row.FindControl("ddlchucvutronglop");
                    Control ctrl = row.FindControl("imgdelete") as ImageButton;
                    if (ctrl != null)
                    {
                        ImageButton img1 = (ImageButton)ctrl;
                        if (img.ClientID == img1.ClientID)
                        {
                            BTbHocVien.UpdateChucVuHVTrongLop(new ETbHocVien
                            {
                                ChucVuTrongLop = "Không",
                                MaHV = Mahv
                            });
                            imgdelete.Visible = false;
                            imgaccept.Visible = false;
                            ddlchucvu.Enabled = true;
                        }
                    }
                }
                foreach (GridViewRow row in gvDiemHV.Rows)
                {
                    DropDownList ddlchucvu = (DropDownList)row.FindControl("ddlchucvutronglop");
                    DataTable dt = tb.GetDataTableById2("TbHocVien_GetChucVuTrongLopByMaLop", ddllophoc.SelectedValue.ToString());
                    if (ddlchucvu.Enabled == true)
                    {
                        LoadChucVuHVTrongLop(ddlchucvu);
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (dt.Rows[i]["ChucVuTrongLop"].ToString() == "Lớp Trưởng")
                            {
                                ddlchucvu.Items.Remove(ddlchucvu.Items.FindByText("Lớp Trưởng"));
                            }
                            if (dt.Rows[i]["ChucVuTrongLop"].ToString() == "Lớp Phó")
                            {
                                ddlchucvu.Items.Remove(ddlchucvu.Items.FindByText("Lớp Phó"));
                            }
                            if (dt.Rows[i]["ChucVuTrongLop"].ToString() == "Bí Thư")
                            {
                                ddlchucvu.Items.Remove(ddlchucvu.Items.FindByText("Bí Thư"));
                            }
                        }
                    }
                }
            }
            catch 
            {
               
            }  
         
        }

        public void Export1(DataTable dt, string sheetName, string title)
        {
            //T?o các ð?i tý?ng Excel
            Microsoft.Office.Interop.Excel.Application oExcel = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbooks oBooks;
            Microsoft.Office.Interop.Excel.Sheets oSheets;
            Microsoft.Office.Interop.Excel.Workbook oBook;
            Microsoft.Office.Interop.Excel.Worksheet oSheet;

            //T?o m?i m?t Excel WorkBook 
            oExcel.Visible = true;
            oExcel.DisplayAlerts = false;
            oExcel.Application.SheetsInNewWorkbook = 1;
            oBooks = oExcel.Workbooks;

            oBook = (Microsoft.Office.Interop.Excel.Workbook)(oExcel.Workbooks.Add(Type.Missing));
            oSheets = oBook.Worksheets;
            oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oSheets.get_Item(1);
            oSheet.Name = sheetName;

            // T?o ph?n ð?u n?u mu?n
            Microsoft.Office.Interop.Excel.Range head = oSheet.get_Range("B1", "E1");
            head.MergeCells = true;
            head.Value2 = title;
            head.Font.Bold = true;
            head.Font.Name = "Tahoma";
            head.Font.Size = "18";
            head.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

            // T?o tiêu ð? c?t 
            Microsoft.Office.Interop.Excel.Range cl1 = oSheet.get_Range("A3", "A3");
            cl1.Value2 = "Mã học viên";
            cl1.ColumnWidth = 13.5;

            Microsoft.Office.Interop.Excel.Range cl2 = oSheet.get_Range("B3", "B3");
            cl2.Value2 = "Họ và tên";
            cl2.ColumnWidth = 13.5;

            Microsoft.Office.Interop.Excel.Range cl3 = oSheet.get_Range("C3", "C3");
            cl3.Value2 = "Số điện thoại";
            cl3.ColumnWidth = 13.5;

            Microsoft.Office.Interop.Excel.Range cl4 = oSheet.get_Range("D3", "D3");
            cl4.Value2 = "Email";
            cl4.ColumnWidth = 13.5;


            Microsoft.Office.Interop.Excel.Range rowHead = oSheet.get_Range("A3", "D3");
            rowHead.Font.Bold = true;
            // K? vi?n
            rowHead.Borders.LineStyle = Microsoft.Office.Interop.Excel.Constants.xlSolid;
            // Thi?t l?p màu n?n
            rowHead.Interior.ColorIndex = 15;
            rowHead.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;


            // T?o m?ng ð?i tý?ng ð? lýu d? toàn b? d? li?u trong DataTable,
            // v? d? li?u ðý?c ðý?c gán vào các Cell trong Excel ph?i thông qua object thu?n.
            object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];

            //Chuy?n d? li?u t? DataTable vào m?ng ð?i tý?ng
            for (int r = 0; r < dt.Rows.Count; r++)
            {
                DataRow dr = dt.Rows[r];
                for (int c = 0; c < dt.Columns.Count; c++)
                {
                    arr[r, c] = dr[c];
                }
            }

            //Thi?t l?p vùng ði?n d? li?u
            int rowStart = 4;
            int columnStart = 1;

            int rowEnd = rowStart + dt.Rows.Count - 1;
            int columnEnd = dt.Columns.Count;

            // Ô b?t ð?u ði?n d? li?u
            Microsoft.Office.Interop.Excel.Range c1 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[rowStart, columnStart];
            // Ô k?t thúc ði?n d? li?u
            Microsoft.Office.Interop.Excel.Range c2 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[rowEnd, columnEnd];
            // L?y v? vùng ði?n d? li?u
            Microsoft.Office.Interop.Excel.Range range = oSheet.get_Range(c1, c2);

            //Ði?n d? li?u vào vùng ð? thi?t l?p
            range.Value2 = arr;

            // K? vi?n
            range.Borders.LineStyle = Microsoft.Office.Interop.Excel.Constants.xlSolid;
            // Cãn gi?a c?t STT
            Microsoft.Office.Interop.Excel.Range c3 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[rowEnd, columnStart];
            Microsoft.Office.Interop.Excel.Range c4 = oSheet.get_Range(c1, c3);
            oSheet.get_Range(c3, c4).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

        }
        protected void btnexport_Click(object sender, EventArgs e)
        {
            ETbHocVien hv = new ETbHocVien();
            hv.MaLop = int.Parse(ddllophoc.SelectedValue.ToString());
            DataTable dt = BTbHocVien.SelectByLopExport(hv);

            Export1(dt, "Danh sach", "DANH SÁCH ĐIỂM HỌC VIÊN");
        }
    }
}